<template>
	<view class="goods-item">
		<view class="image-wrapper">
			<cl-image
				mode="aspectFill"
				background-color="#fff"
				:size="[350, 350]"
				:radius="[16, 16, 0, 0]"
				:src="'https://shop.sdamdyy.cn/' + (item.mainPic || '')"
				fallback="/static/empty/no.jpg"
			/>

			<!-- 近效期标签 -->
			<view class="expiry-badge" v-if="daysToExpiry">
				<text class="days">{{ daysToExpiry }}</text>
				<text class="unit">天</text>
			</view>

			<!-- 库存状态 -->
			<view class="stock-badge" :class="stockStatus.class">
				{{ stockStatus.text }}
			</view>
		</view>

		<view class="goods-item__det">
			<!-- 商品名称 -->
			<cl-text
				:value="item.title || item.oracleGoodsName"
				block
				:margin="[0, 0, 8, 0]"
				:ellipsis="2"
				:line-height="1.4"
			/>

			<!-- 规格信息 -->
			<view class="spec-info">
				<text class="spec">{{ item.goodsSpec }}</text>
				<text class="unit" v-if="item.unit">{{ item.unit }}</text>
			</view>

			<!-- 生产厂家 -->
			<view class="manufacturer" v-if="item.manufacturer">
				{{ item.manufacturer }}
			</view>

			<!-- 效期信息 -->
			<view class="expiry-info">
				<cl-icon name="time" color="#ff6b6b" :size="24" />
				<text>效期至：{{ formatDate(item.nearestExpiredDate) }}</text>
			</view>

			<!-- 中包装信息 -->
			<view class="package-info" v-if="item.midPackage">
				<cl-tag type="info" size="mini"
					>中包装：{{ item.midPackage }}{{ item.unit }}</cl-tag
				>
				<cl-tag v-if="item.canSplit" type="success" size="mini">可拆分</cl-tag>
				<cl-tag v-else type="warning" size="mini">不可拆分</cl-tag>
			</view>

			<!-- 价格信息 -->
			<view class="price-section">
				<view class="price-row" v-if="user.token">
					<view class="near-expiry-price">
						<text class="value">{{
							formatUserPrice(item.nextValPrice, user, item.noDiscounts)
						}}</text>
					</view>
					<view class="original-price" v-if="item.price">
						{{ formatUserPrice(item.nextValPrice, user, 1) }}
					</view>
				</view>
				<view v-else class="login-tip"> 登录查看价格 </view>
			</view>

			<!-- 购买操作区 -->
			<view class="action-section" v-if="user.token">
				<!-- 数量选择 -->
				<view class="quantity-control">
					<text class="quantity-label">数量：</text>
					<cl-input-number
						v-model="quantity"
						:min="minQuantity"
						:max="maxQuantity"
						:step="step"
						:size="30"
						:disabled="stockStatus.class === 'out-stock'"
					/>
				</view>

				<!-- 直接下单按钮 -->
				<cl-button
					type="danger"
					size="small"
					round
					:disabled="!canOrder"
					:loading="loading"
					@tap="handleDirectOrder"
				>
					立即下单
				</cl-button>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import type { PropType } from "vue";
import { ref, computed } from "vue";
import { useCool } from "/@/cool";
import { useStore } from "/@/cool/store";
import { formatUserPrice } from "/@/utils/price";

const props = defineProps({
	item: {
		type: Object as PropType<any>,
		default: () => ({}),
	},
});

const { service, router } = useCool();
const { user } = useStore();

// 购买数量
const quantity = ref(1);
// 加载状态
const loading = ref(false);

// 计算距离过期天数
const daysToExpiry = computed(() => {
	if (!props.item.nearestExpiredDate) return 0;
	const expiryDate = new Date(props.item.nearestExpiredDate);
	const today = new Date();
	const days = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
	return Math.max(0, days);
});

// 计算库存状态
const stockStatus = computed(() => {
	const stock = Number(props.item.nearStorNum || 0);
	if (stock === 0) {
		return { text: "无货", class: "out-stock" };
	} else if (stock < 100) {
		return { text: "紧张", class: "low-stock" };
	} else {
		return { text: "充足", class: "in-stock" };
	}
});

// 计算折扣百分比
const discountPercent = computed(() => {
	if (!props.item.price || !props.item.nextValPrice) return "";
	const original = parseFloat(props.item.price);
	const nearExpiry = parseFloat(props.item.nextValPrice);
	if (original === 0) return "";
	const percent = ((nearExpiry / original) * 10).toFixed(1);
	return percent.endsWith(".0") ? percent.slice(0, -2) : percent;
});

// 最小购买数量
const minQuantity = computed(() => {
	// 如果不能拆分，最小购买量为中包装数量
	if (!props.item.canSplit && props.item.midPackage) {
		return Number(props.item.midPackage) || 1;
	}
	return 1;
});

// 最大购买数量
const maxQuantity = computed(() => {
	return Number(props.item.nearStorNum || 0);
});

// 步进值
const step = computed(() => {
	// 如果不能拆分，步进为中包装数量
	if (!props.item.canSplit && props.item.midPackage) {
		return Number(props.item.midPackage) || 1;
	}
	return 1;
});

// 是否可以下单
const canOrder = computed(() => {
	const stock = Number(props.item.nearStorNum || 0);
	return stock > 0 && quantity.value > 0 && quantity.value <= stock;
});

// 格式化日期
function formatDate(date: string) {
	if (!date) return "";
	const d = new Date(date);
	return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
		d.getDate()
	).padStart(2, "0")}`;
}

// 直接下单
async function handleDirectOrder() {
	if (!canOrder.value) return;

	// 确认下单
	uni.showModal({
		title: "确认下单",
		content: `确认购买「${props.item.title || props.item.oracleGoodsName}」${quantity.value}${
			props.item.unit || "个"
		}？\n请确认后购买。`,
		confirmText: "确认下单",
		cancelText: "取消",
		success: async (res) => {
			if (res.confirm) {
				await createOrder();
			}
		},
	});
}

// 创建订单
async function createOrder() {
	loading.value = true;

	try {
		// 1. 先添加到购物车（带近效期标记）
		const cartRes = await service.order.cart.addCart({
			goodsId: props.item.goodsId,
			num: quantity.value,
			isNextValPrice: true, // 近效期价格标记
		});

		if (!cartRes.cardId) {
			throw new Error("添加购物车失败");
		}

		// 2. 直接从购物车创建订单
		await service.order.info.createFromCart({
			cartIds: [cartRes.cardId],
			isNextValPrice: true, // 近效期订单标记
		});

		uni.showToast({
			title: "下单成功",
			icon: "success",
		});

		// 重置数量
		quantity.value = minQuantity.value;

		// 跳转到订单列表
		setTimeout(() => {
			router.push("/pages/order/list");
		}, 1500);
	} catch (error: any) {
		uni.showToast({
			title: error.message || "下单失败",
			icon: "none",
		});
	} finally {
		loading.value = false;
	}
}
</script>

<style lang="scss" scoped>
.goods-item {
	position: relative;
	background-color: #ffffff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.image-wrapper {
		position: relative;
		width: 100%;
		height: 350rpx;

		.expiry-badge {
			position: absolute;
			top: 16rpx;
			left: 16rpx;
			background: linear-gradient(135deg, #ff6b6b, #ff5252);
			color: #fff;
			padding: 8rpx 16rpx;
			border-radius: 24rpx;
			display: flex;
			align-items: baseline;
			gap: 4rpx;
			box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.3);

			.days {
				font-size: 32rpx;
				font-weight: 600;
			}

			.unit {
				font-size: 20rpx;
			}
		}

		.stock-badge {
			position: absolute;
			top: 16rpx;
			right: 16rpx;
			padding: 6rpx 16rpx;
			border-radius: 20rpx;
			font-size: 24rpx;
			font-weight: 500;

			&.in-stock {
				background-color: #52c41a;
				color: #fff;
			}

			&.low-stock {
				background-color: #faad14;
				color: #fff;
			}

			&.out-stock {
				background-color: #ff4d4f;
				color: #fff;
			}
		}
	}

	.goods-item__det {
		padding: 20rpx;

		.spec-info {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: 24rpx;
			color: #666;
			margin-bottom: 8rpx;

			.spec {
				color: #666;
			}

			.unit {
				color: #999;
			}
		}

		.manufacturer {
			font-size: 22rpx;
			color: #999;
			margin-bottom: 12rpx;
		}

		.expiry-info {
			display: flex;
			align-items: center;
			gap: 8rpx;
			padding: 8rpx 0;
			margin-bottom: 8rpx;

			text {
				font-size: 24rpx;
				color: #ff6b6b;
				font-weight: 500;
			}
		}

		.package-info {
			display: flex;
			align-items: center;
			gap: 8rpx;
			margin-bottom: 12rpx;
			flex-wrap: wrap;
		}

		.price-section {
			margin-bottom: 12rpx;

			.price-row {
				display: flex;
				align-items: baseline;
				gap: 12rpx;

				.near-expiry-price {
					display: flex;
					align-items: baseline;
					color: #ff4444;

					.value {
						font-size: 32rpx;
						font-weight: 600;
					}
				}

				.original-price {
					font-size: 22rpx;
					color: #999;
					text-decoration: line-through;
				}

				.discount-rate {
					background: linear-gradient(135deg, #ff6b6b, #ff5252);
					color: #fff;
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
					font-size: 20rpx;
					font-weight: 500;
				}
			}

			.login-tip {
				font-size: 28rpx;
				color: #ff6b6b;
			}
		}

		.stock-info {
			font-size: 24rpx;
			color: #666;
			margin-bottom: 12rpx;
		}

		.action-section {
			display: flex;
			flex-direction: column;
			gap: 12rpx;
			padding-top: 12rpx;
			border-top: 1rpx solid #f0f0f0;

			.quantity-control {
				display: flex;
				align-items: center;
				gap: 12rpx;

				.quantity-label {
					font-size: 26rpx;
					color: #333;
					font-weight: 500;
				}
			}
		}
	}
}
</style>
